from fastapi import APIRouter, Depends, HTTPException, Query
from typing import List, Optional

from app.core.deps import get_current_active_user
from app.core.security import get_password_hash
from app.models.models import User, Role, Department, UserRole
from app.schemas.user import UserCreate, UserUpdateAdmin as UserUpdate, UserOut
from app.schemas.base import ResponseBase, PageResponseBase, PageInfo

router = APIRouter()

@router.get("/", response_model=PageResponseBase[List[UserOut]])
async def get_users(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页条数"),
    username: Optional[str] = Query(None, description="用户名"),
    name: Optional[str] = Query(None, description="姓名"),
    status: Optional[bool] = Query(None, description="状态"),
    department_id: Optional[int] = Query(None, description="部门ID"),
    _: User = Depends(get_current_active_user)
):
    """获取用户列表"""
    # 构建查询条件
    query = {}
    if username:
        query["username__contains"] = username
    if name:
        query["name__contains"] = name
    if status is not None:
        query["status"] = status
    if department_id:
        query["department_id"] = department_id
    
    # 查询总数
    total = await User.filter(**query).count()
    
    # 分页查询，预加载关联数据
    users = await User.filter(**query).offset((page - 1) * page_size).limit(page_size).prefetch_related("department").all()
    
    # 构建用户列表
    user_list = []
    for user in users:
        # 获取用户角色 - 通过关联表查询
        user_role_relations = await UserRole.filter(user_id=user.id).prefetch_related('role').all()
        roles = []
        for relation in user_role_relations:
            role = relation.role
            roles.append({"id": role.id, "name": role.name, "code": role.code})
        
        # 获取部门名称
        department_name = None
        if user.department_id and user.department:
            department_name = user.department.name
        
        # 构建用户信息
        user_data = {
            "id": user.id,
            "username": user.username,
            "name": user.name,
            "email": user.email,
            "phone": user.phone,
            "avatar": user.avatar,
            "status": user.status,
            "department_id": user.department_id,
            "department_name": department_name,
            "roles": roles,
            "created_at": user.created_at,
            "updated_at": user.updated_at
        }
        
        user_list.append(UserOut(**user_data))
    
    # 构建分页信息
    page_info = PageInfo(page=page, page_size=page_size, total=total)
    
    return PageResponseBase[List[UserOut]](
        data=user_list,
        page_info=page_info
    )

@router.post("/", response_model=ResponseBase[UserOut])
async def create_user(
    user_in: UserCreate,
    _: User = Depends(get_current_active_user)
):
    """创建用户"""
    # 检查用户名是否已存在
    if await User.filter(username=user_in.username).exists():
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 检查部门是否存在
    if user_in.department_id and not await Department.filter(id=user_in.department_id).exists():
        raise HTTPException(status_code=400, detail="部门不存在")
    
    # 创建用户
    user = await User.create(
        username=user_in.username,
        password=get_password_hash(user_in.password),
        name=user_in.name,
        email=user_in.email,
        phone=user_in.phone,
        avatar=user_in.avatar,
        status=user_in.status,
        department_id=user_in.department_id
    )
    
    # 添加角色
    if user_in.role_ids:
        for role_id in user_in.role_ids:
            await UserRole.create(user_id=user.id, role_id=role_id)
    
    # 重新获取用户信息，包含关联数据
    user = await User.filter(id=user.id).prefetch_related("department").first()
    
    # 获取用户角色 - 通过关联表查询
    user_role_relations = await UserRole.filter(user_id=user.id).prefetch_related('role').all()
    roles = []
    for relation in user_role_relations:
        role = relation.role
        roles.append({"id": role.id, "name": role.name, "code": role.code})
    
    # 获取部门名称
    department_name = None
    if user.department_id and user.department:
        department_name = user.department.name
    
    # 构建用户信息
    user_data = {
        "id": user.id,
        "username": user.username,
        "name": user.name,
        "email": user.email,
        "phone": user.phone,
        "avatar": user.avatar,
        "status": user.status,
        "department_id": user.department_id,
        "department_name": department_name,
        "roles": roles,
        "created_at": user.created_at,
        "updated_at": user.updated_at
    }
    
    return ResponseBase[UserOut](data=UserOut(**user_data))

@router.get("/{user_id}", response_model=ResponseBase[UserOut])
async def get_user(
    user_id: int,
    _: User = Depends(get_current_active_user)
):
    """获取用户详情"""
    user = await User.filter(id=user_id).prefetch_related("department").first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 获取用户角色 - 通过关联表查询
    user_role_relations = await UserRole.filter(user_id=user.id).prefetch_related('role').all()
    roles = []
    for relation in user_role_relations:
        role = relation.role
        roles.append({"id": role.id, "name": role.name, "code": role.code})
    
    # 获取部门名称
    department_name = None
    if user.department_id and user.department:
        department_name = user.department.name
    
    # 构建用户信息
    user_data = {
        "id": user.id,
        "username": user.username,
        "name": user.name,
        "email": user.email,
        "phone": user.phone,
        "avatar": user.avatar,
        "status": user.status,
        "department_id": user.department_id,
        "department_name": department_name,
        "roles": roles,
        "created_at": user.created_at,
        "updated_at": user.updated_at
    }
    
    return ResponseBase[UserOut](data=UserOut(**user_data))

@router.put("/{user_id}", response_model=ResponseBase[UserOut])
async def update_user(
    user_id: int,
    user_in: UserUpdate,
    _: User = Depends(get_current_active_user)
):
    """更新用户"""
    user = await User.filter(id=user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查用户名是否已存在
    if user_in.username and user_in.username != user.username:
        if await User.filter(username=user_in.username).exists():
            raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 检查部门是否存在
    if user_in.department_id and not await Department.filter(id=user_in.department_id).exists():
        raise HTTPException(status_code=400, detail="部门不存在")
    
    # 更新用户信息
    update_data = user_in.dict(exclude_unset=True)
    if "password" in update_data:
        update_data["password"] = get_password_hash(update_data["password"])
    
    if "role_ids" in update_data:
        role_ids = update_data.pop("role_ids")
        # 清空原有角色
        await UserRole.filter(user_id=user.id).delete()
        # 添加新角色
        if role_ids:
            for role_id in role_ids:
                await UserRole.create(user_id=user.id, role_id=role_id)
    
    # 更新用户
    await user.update_from_dict(update_data)
    await user.save()
    
    # 重新获取用户信息，包含关联数据
    user = await User.filter(id=user.id).prefetch_related("department").first()
    
    # 获取用户角色 - 通过关联表查询
    user_role_relations = await UserRole.filter(user_id=user.id).prefetch_related('role').all()
    roles = []
    for relation in user_role_relations:
        role = relation.role
        roles.append({"id": role.id, "name": role.name, "code": role.code})
    
    # 获取部门名称
    department_name = None
    if user.department_id and user.department:
        department_name = user.department.name
    
    # 构建用户信息
    user_data = {
        "id": user.id,
        "username": user.username,
        "name": user.name,
        "email": user.email,
        "phone": user.phone,
        "avatar": user.avatar,
        "status": user.status,
        "department_id": user.department_id,
        "department_name": department_name,
        "roles": roles,
        "created_at": user.created_at,
        "updated_at": user.updated_at
    }
    
    return ResponseBase[UserOut](data=UserOut(**user_data))

@router.delete("/{user_id}", response_model=ResponseBase)
async def delete_user(
    user_id: int,
    _: User = Depends(get_current_active_user)
):
    """删除用户"""
    user = await User.filter(id=user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 删除用户
    await user.delete()
    
    return ResponseBase()